﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace HelloASPX
{
    public partial class AddProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                HttpContext.Current.Response.Write("<script>alert('请先登陆！');location='Login.aspx'</script>");
            }
        }

        protected void addProductButton_Click(object sender, EventArgs e)
        {
            if(ProductName.Text == "" || ProductTime.Text == "" || FileUpload1.FileName == "" || ProductPrice.Text == "" || ProductInfo.Text == "")
            {
                Response.Write("<script>alert('您填写的信息不完善！');</script>");
                return;
            }
            XmlDocument doc = new XmlDocument();

            doc.Load(Server.MapPath("~/App_Data/products.xml"));
            XmlNodeList productsList = doc.SelectNodes("//product");


            XmlElement productnode = doc.CreateElement("product");

            XmlElement productidnode = doc.CreateElement("pid");
            productidnode.InnerText = productsList.Count + 1 + "";
            productnode.AppendChild(productidnode);

            XmlElement productnamenode = doc.CreateElement("pname");
            productnamenode.InnerText = ProductName.Text;
            productnode.AppendChild(productnamenode);

            XmlElement producttimenode = doc.CreateElement("ptime");
            producttimenode.InnerText = ProductTime.Text;
            productnode.AppendChild(producttimenode);

            XmlElement productimagenode = doc.CreateElement("pimage");
            string photopath = "~/img/products/" + FileUpload1.FileName;
            productimagenode.InnerText = photopath;
            productnode.AppendChild(productimagenode);

            XmlElement productpricenode = doc.CreateElement("pprice");
            productpricenode.InnerText = ProductPrice.Text;
            productnode.AppendChild(productpricenode);

            XmlElement productinfonode = doc.CreateElement("pinfo");
            productinfonode.InnerText = ProductInfo.Text;
            productnode.AppendChild(productinfonode);

            doc.DocumentElement.AppendChild(productnode);
            doc.Save(Server.MapPath("~/App_Data/products.xml"));

            Response.Write("<script>alert('添加成功');location='ProductList.aspx'</script>");
        }

        protected void SelectProductButton_Click(object sender, EventArgs e)
        {
            Response.Write("<script>location='SelectProduct.aspx'</script>");
        }
    }
}